<?php

namespace App\Console\Commands;

use App\Order;
use App\Wechat;
use Illuminate\Console\Command;
use DB;
use EasyWeChat\Factory;


class Refund extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orders:refund';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单退款';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->check();
        $config = [
            // 必要配置
            'app_id' => env('WECHAT_APPID'),
            'mch_id' => env('WECHAT_MCH_ID'),
            'key' => env('WECHAT_KEY'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => public_path('/wechatPem/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path' => public_path('/wechatPem/apiclient_key.pem'), // XXX: 绝对路径！！！！

            'notify_url' => Wechat::NOTIFY_URL,     // 你也可以在下单时单独设置来想覆盖它
        ];

        $app = Factory::payment($config);
        $i = 0;
        $status = join(',', Order::$win);
        $sql = "SELECT order_num FROM s_order WHERE is_win IN ($status) AND DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(ctime) ";
        $orders = DB::select($sql);
        //如果数据不为空
        if (count($orders) > 0) {
            foreach ($orders as $order) {
                //订单信息
                $order_num = $order->order_num;
                $order = Order::where('order_num', $order_num)->first();
                if (!$order) {
                    return response()->json(['code' => 500, 'msg' => '订单信息有误']);
                }
                $price = bcmul($order->price, 100, 0);
                $result = $app->refund->byOutTradeNumber($order_num, $order_num.'1', $price, $price, [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '活动结束金额返还',
                ]);
                if ($result['return_code'] === "SUCCESS" && $result['result_code'] === "SUCCESS") {
                    $i++;
                }
            }
        }
        logger($i . '个退款成功');
        exit($i . '个退款成功');
    }

    public function check()
    {
        $file = 'orders_refund.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
